import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android_flutter/common_ui/web/webview_page.dart';
import 'package:wan_android_flutter/common_ui/web/webview_widget.dart';
import 'package:wan_android_flutter/routes/RouteUtils.dart';

import '../../common_ui/smart_refresh/smart_refresh_widget.dart';
import '../../repository/datas/home_list_model.dart';
import 'home_vm.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _InitBanner();
  }

  void _InitBanner() async {
    viewModel.getBanner();
    viewModel.initDataList(false);
  }

  void refreshOrLoad(bool loadMore) {
    viewModel.initDataList(loadMore, callBack: (loadMore) {
      if (loadMore) {
        refreshController.loadComplete();
      } else {
        refreshController.refreshCompleted();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ChangeNotifierProvider<HomeViewModel>(
        create: (context) {
          return viewModel;
        },
        child: Scaffold(
            body: SafeArea(
                child: SmartRefreshWidget(
          controller: refreshController,
          onLoading: () {
            //上拉加载
            refreshOrLoad(true);
          },
          onRefresh: () {
            //下拉刷新
            viewModel.getBanner().then((onValue) {
              refreshOrLoad(false);
            });
          },
          child: SingleChildScrollView(
            // 滑动组件
            child: Column(
              children: [_banner(callback: (index){
                RouteUtils.push(
                    context,
                    WebViewPage(
                      loadResource: viewModel.bannerList?[index]?.url ?? "",
                      webViewType: WebViewType.URL,
                      showTitle: true,
                      title: viewModel.bannerList?[index]?.title,
                    ));
              }), _homeListView()],
            ),
          ),
        ))));
  }

  Widget _homeListView() {
    return Consumer<HomeViewModel>(builder: (context, value, child) {
      return ListView.builder(
        shrinkWrap: true, //计算屏幕显示高度
        physics: NeverScrollableScrollPhysics(), //禁用listView滑动事件
        itemBuilder: (context, index) {
          return _listview_itemview(value.dataList?[index], index,onTap: (){
            RouteUtils.push(
                context,
                WebViewPage(
                  loadResource: value.dataList?[index].link ?? "",
                  webViewType: WebViewType.URL,
                  showTitle: true,
                  title: value.dataList?[index].title,
                ));
          });
        },
        itemCount: value.dataList?.length ?? 0,
      );
    });
  }

  Widget _banner({ValueChanged<int>? callback}) {
    return Consumer<HomeViewModel>(builder: (context, value, child) {
      return SizedBox(
        height: 150.h,
        width: double.infinity,
        child: Swiper(
          indicatorLayout: PageIndicatorLayout.COLOR,
          autoplay: true,
          pagination: const SwiperPagination(),
          control: const SwiperControl(),
          itemCount: value.bannerList?.length ?? 0,
          itemBuilder: (context, index) {
            return GestureDetector(onTap: (){
              callback?.call(index);
            },child: Container(
                margin: EdgeInsets.all(15.r),
                height: 150.h,
                color: Colors.blueGrey,
                child: Image.network(
                  value.bannerList?[index]?.imagePath ?? "",
                  fit: BoxFit.fill,
                )));
          },
        ),
      );
    });
  }

  Widget _listview_itemview(HomeListItemData? item, int index,{GestureTapCallback? onTap}) {
    // return InkWell() //点击时有水波纹效果
    return GestureDetector(
        onTap: onTap,
        child: Container(
          margin:
              EdgeInsets.only(left: 10.w, right: 10.w, top: 5.h, bottom: 5.h),
          padding:
              EdgeInsets.only(left: 10.w, right: 10.w, top: 15.h, bottom: 15.h),
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black12),
              borderRadius: BorderRadius.all(Radius.circular(6.r))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ClipRRect(
                      borderRadius: BorderRadius.circular(15.r),
                      child: Image.asset(
                        "assets/head/preview.jpg",
                        width: 30.r,
                        height: 30.r,
                        fit: BoxFit.fill,
                      )),
                  SizedBox(width: 5.w),
                  Text(
                    (item?.author == null || item!.author!.isEmpty)
                        ? item?.shareUser ?? ""
                        : item.author ?? "",
                    style: TextStyle(color: Colors.black),
                  ),
                  Expanded(child: SizedBox()),
                  Text(
                    item?.niceShareDate ?? "",
                    style: TextStyle(color: Colors.black, fontSize: 12.sp),
                  ),
                  SizedBox(width: 5.w),
                  (item?.type == 1)
                      ? Text(
                          "置顶",
                          style: TextStyle(
                              color: Colors.blue, fontWeight: FontWeight.bold),
                        )
                      : SizedBox(),
                ],
              ),
              // Row(children: [
              SizedBox(
                height: 5.h,
              ),
              Text(
                item?.title ?? "",
                style: TextStyle(color: Colors.black, fontSize: 14.sp),
              ),
              SizedBox(
                height: 5.h,
              ),
              // ],
              // ),
              Row(
                children: [
                  Text(
                    item?.chapterName ?? "",
                    style: TextStyle(color: Colors.green, fontSize: 12.sp),
                  ),
                  Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: () {
                      viewModel.collect("${item?.id}", index,
                          item?.collect == true ? false : true);
                    },
                    child: Image.asset(
                        item?.collect == true
                            ? "assets/images/img_collect.png"
                            : "assets/images/img_collect_grey.png",
                        width: 30.r,
                        height: 30.r),
                  )
                ],
              )
            ],
          ),
        ));
  }
}
